<template>
  <div class="addAward-container-padding">
    <div class="buttonList">
      <el-button type="primary" @click="save">保存为草稿</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-divider />
    <div>
      <label class="label">课题名称：</label>
      <el-select
        v-model="projectName"
        placeholder="请选择"
        filterable
        style="width: 236px"
        @change="selectProject"
      >
        <el-option
          v-for="j in ProjectList"
          :key="j.topicId"
          :label="j.topicName"
          :value="j.topicId"
        />
      </el-select>
    </div>
    <el-descriptions title="" class="margin-top20">
      <el-descriptions-item
        v-for="(item, index) in topicDescriptions"
        :key="index"
        :label="item.label"
      >
        {{ TopicAndProject[item.value] }}
      </el-descriptions-item>
    </el-descriptions>
    <el-divider />
    <div class="title margin-top20">一、项目基本情况</div>
    <Form1 ref="child" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">二、推荐项目简介</div>
    <Form2
      ref="child2"
      :is-craft="type"
      :is-update="isUpdate"
      class="margin-top20"
    />
    <div class="title margin-top20">三、推荐理由</div>
    <Form3
      ref="child3"
      :is-craft="type"
      :is-update="isUpdate"
      class="margin-top20"
    />
    <div class="title margin-top20">四、经济效益情况表（单位：万元）</div>
    <Form4
      ref="child4"
      :is-craft="type"
      :is-update="isUpdate"
      class="margin-top20"
    />
    <div class="title margin-top20">五、已获奖励情况</div>
    <Form5 ref="child5" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">六、专利情况</div>
    <Form6 ref="child6" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">七、技术秘密</div>
    <Form7 ref="child7" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">
      八、主要完成人情况表
      <span class="subtitle">
        (注：1、按申报奖励等级填报人数，特等奖20人，一等奖12名，二等奖10名，三等奖8名)
      </span>
    </div>
    <Form8 ref="child8" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">九、主要完成单位情况</div>
    <Form9 ref="child9" :is-update="isUpdate" class="margin-top20" />
    <div class="title margin-top20">十、推荐意见</div>
    <Form10 ref="child10" :is-update="isUpdate" class="margin-top20" />
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted } from 'vue'
  import { topicDescriptions } from '../table/column'
  import Form1 from './form1.vue'
  import Form2 from './form2.vue'
  import Form3 from './form3.vue'
  import Form4 from './form4.vue'
  import Form5 from './form5.vue'
  import Form6 from './form6.vue'
  import Form7 from './form7.vue'
  import Form8 from './form8.vue'
  import Form9 from './form9.vue'
  import Form10 from './form10.vue'
  import { selectTopicList, queryTopicAndProject } from '@/api/project/index'
  import { useDictStore } from '@/store/modules/dict'
  import { VxePagerEvents } from 'vxe-table'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { storeToRefs } from 'pinia'
  import {
    addAchievement,
    getAchievementInfo,
    updateAchievement,
  } from '@/api/achievementAward'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'
  import { postDraftBoxCreate } from '@/api/project/drafts'
  const dictStore = useDictStore()
  const topicList = dictStore.getDictType('topic_type')
  const { closeTabNavigate } = useCloseTabNavigate()
  const route = useRoute()
  const id = ref()

  const projectName = ref('')
  const ProjectList = ref([])
  const child = ref()
  const child2 = ref()
  const child3 = ref()
  const child4 = ref()
  const child5 = ref()
  const child6 = ref()
  const child7 = ref()
  const child8 = ref()
  const child9 = ref()
  const child10 = ref()

  const getTopic = () => {
    selectTopicList({ type: 1 }).then((res: any) => {
      if (res.code == 0 || res.code == 200) {
        const list = res.data
        ProjectList.value = ProjectList.value.concat(list)
      }
    })
  }
  const isUpdate = ref(false)
  onMounted(() => {
    getTopic()
    id.value = route.query.id
    type.value = topicList.filter(
      (item) => item.value == route.query.isCraft
    )[0]?.label
    if (id.value) {
      getInfo(id.value)
    }
  })

  const type = ref('')
  const TopicAndProject = ref({}) as any

  const selectProject = (value) => {
    queryTopicAndProject({ topicId: value }).then((res: any) => {
      if (res.code == 0 || res.code == 200) {
        TopicAndProject.value = {
          ...res.data.topicRespVO,
          ...res.data.projectInfoRespVO,
        }
        const startDate = dayjs(TopicAndProject.value.researchStartDate).format(
          'YYYY-MM-DD'
        )
        const endDate = dayjs(TopicAndProject.value.researchEndDate).format(
          'YYYY-MM-DD'
        )
        TopicAndProject.value.researchDate = `${startDate}-${endDate}`
        type.value = topicList.filter(
          (item) => item.value == res.data.topicRespVO.type
        )[0]?.label
      }
    })
  }

  // 保存为草稿
  const save = async () => {
    await child.value.submit()
    await child2.value.submit()
    await child3.value.submit()
    await child4.value.submit()
    await child5.value.submit()
    await child6.value.submit()
    await child7.value.submit()
    await child8.value.submit()
    await child9.value.submit()
    await child10.value.submit()
    try {
      await store.addForm({ topicId: projectName.value })
      const params = {
        id: route.query.id || '',
        type: 'TECH_PRAISE',
        submitJson: JSON.stringify({
          ...allForm.value,
          draftBoxId: route.query?.id || '',
        }),
      }
      const res: any = await postDraftBoxCreate(params)
      if (res && res.code === 0) {
        ElMessage.success('保存草稿成功')
        // baseInfoRef.value.resetFields()
        closeTabNavigate({ name: 'innovate' })
      } else {
        ElMessage.error(`保存草稿失败: ${res.msg || '未知错误'}`)
      }
    } catch (e) {
      console.error('保存草稿失败', e)
    }
  }

  const store = useAchievementAwardStore()
  const { allForm } = storeToRefs(store)
  // 提交表单
  const submit = async () => {
    const promises = [
      child.value.submit(),
      child2.value.submit(),
      child3.value.submit(),
      child4.value.submit(),
      child5.value.submit(),
      child6.value.submit(),
      child7.value.submit(),
      child8.value.submit(),
      child9.value.submit(),
      child10.value.submit(),
    ]

    try {
      await Promise.all(
        promises.map((promise) =>
          promise.catch((error) => {
            ElMessage.error('提交失败，请重试')
            throw error // 重新抛出错误以便 Promise.all 捕获
          })
        )
      )
    } catch (error) {
      return
    }

    const handleSuccess = () => {
      store.resetForm()
      closeTabNavigate({ name: 'AchievementAward' })
    }

    if (id.value) {
      await store.addForm({ topicId: projectName.value, id: id.value })
      updateAchievement(allForm.value)
        .then((res) => {
          if (res) {
            ElMessage.success('修改成功')
            handleSuccess()
          } else {
            ElMessage.error('修改失败，请重试')
          }
        })
        .catch((error) => {
          ElMessage.error('修改失败，请重试')
        })
    } else {
      await store.addForm({ topicId: projectName.value })
      console.log(allForm.value, '新增')
      addAchievement(allForm.value)
        .then((res) => {
          if (res) {
            ElMessage.success('添加成功')
            handleSuccess()
          } else {
            ElMessage.error('添加失败，请重试')
          }
        })
        .catch((error) => {
          ElMessage.error('添加失败，请重试')
        })
    }
  }

  const getInfo = (id: number | string) => {
    let getType = route.query.getType ?? 2
    getAchievementInfo({ id, getType }).then((res) => {
      const data = res.data
      projectName.value = data?.topicId
      selectProject(projectName.value)
      isUpdate.value = true
      store.setForm(data)
    })
  }

  const tablePage = reactive({
    total: 0,
    currentPage: 1,
    pageSize: 10,
  })

  const handlePageChange: VxePagerEvents.PageChange = ({
    currentPage,
    pageSize,
  }) => {
    tablePage.currentPage = currentPage
    tablePage.pageSize = pageSize
  }

  const height = ref(0)
  interface BaseTableHeight {
    (padding: number): number
  }
  const $baseTableHeight = inject<BaseTableHeight>('$baseTableHeight')
  onBeforeMount(() => {
    window.addEventListener('resize', handleHeight)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleHeight)
  })

  const handleHeight = () => {
    height.value = $baseTableHeight(0)
  }
</script>

<style scoped lang="scss">
  $margin-bottom: 20px;

  .margin-left20 {
    margin-left: $margin-bottom;
  }

  .buttonList {
    display: flex;
    justify-content: end;
    padding-bottom: $margin-bottom;
    border-bottom: 1px solid #edeff2;
    margin-bottom: $margin-bottom;
  }

  .title {
    border-radius: 2px;
    border-left: 5px solid #1890ff;
    height: 28px;
    background: #f7f8f9;
    font-weight: 500;
    font-size: 14px;
    color: #606266;
    padding-left: 12px;
    line-height: 28px;
    margin-bottom: $margin-bottom;
  }

  .margin-bottom0 {
    margin-bottom: 0 !important;
  }

  .margin-top20 {
    margin-top: 20px;
  }

  .demo-form-inline {
    display: grid;
    grid-template-columns: 1fr;
    grid-row-gap: 16px;
    grid-column-gap: 20px;

    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .flexBox {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 20px;
  }

  .formCard {
    border-radius: 4px;

    .formCardtitle {
      background: #e7f3ff;
      font-size: 12px;
      color: #7d8398;
      padding-left: 10px;
      height: 24px;
      line-height: 24px;
      border-radius: 4px 4px 0 0;
    }

    .cardForm {
      background: #f6fbff;
      padding: 20px;
      border-radius: 0 0 4px 4px;
    }
  }

  .demo-form {
    :deep(.el-form-item__content) {
      display: block;
    }

    .el-input {
      --el-input-width: 50%;
    }

    .el-select {
      --el-select-width: 50%;
    }
  }

  .last {
    margin-top: $margin-bottom;
  }

  :deep(.el-descriptions__title) {
    padding-left: 0 !important;
    border-left: 0 !important;
  }

  .subtitle {
    font-size: 12px;
    color: #7d8398;
    margin-left: 10px;
  }
</style>
